import {createRouter,createWebHashHistory} from 'vue-router'
import Login from '@/views/login.vue'

const token = localStorage.getItem('token')

const routes = [
    {
        path:'/login',
        component:Login,
        name:'login',
        meta: { requiresNoAuth: true }
    },
    {
        path:'/',
        redirect:'/login'
    },
    {
        path:'/newUser',
        component:()=>import('@/views/newUser/index.vue'),
        meta: { requiresAuth: true }
    },
    {
        path:'/view',
        component:()=>import('@/views/view/index.vue'),
        meta: { requiresAuth: true }
    },
    {
        path:'/details',
        component:()=>import("@/views/details/index.vue"),
        meta: { requiresAuth: true }
    }
]


const router = createRouter({
    routes,
    history:createWebHashHistory()
})
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token') // 每次路由变化时获取最新token
  
  // 如果路由需要认证但无token
  if (to.matched.some(record => record.meta.requiresAuth) && !token) {
    next('/login')
    return
  }
  
  // 如果路由不需要认证但有token（如登录页）
  if (to.matched.some(record => record.meta.requiresNoAuth) && token) {
    next('/details') // 直接跳转到详情页
    return
  }
  
  // 如果是首次访问根路径且有token
  if (to.path === '/' && token) {
    next('/details') // 直接跳转到详情页
    return
  }
  
  // 其他情况正常放行
  next()
})

export default router